package com.efast.cafe.commponent.es.socketio.listener;

import java.util.List;

import org.slf4j.event.Level;

import com.alibaba.fastjson.JSONArray;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.ExceptionListenerAdapter;
import com.efast.cafe.commponent.es.common.enums.ServiceTypeEnum;
import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;
import com.efast.cafe.framework.constant.FrameConstant;

import io.netty.channel.ChannelHandlerContext;

public class SocketIOExceptionListener extends ExceptionListenerAdapter{

	private static final CafeLogger log = CafeLoggerFactory.getLogger(SocketIOExceptionListener.class,ServiceTypeEnum.SOCKETIO.name());
	
	private boolean enableLog = false;
	
	public SocketIOExceptionListener(boolean enableLog){
		this.enableLog = enableLog;
	}
	
	@Override
	public void onEventException(Exception e, List<Object> data, SocketIOClient client) {
		 log.error(e.getMessage(), e);
		 if(enableLog)
			 log.cacheLog(Level.ERROR, JSONArray.toJSONString(data)+" Error Message:"+e.getMessage(), "onEventException,UID:"+client.get(FrameConstant.SOCKET_UID));
	}
	
	@Override
	public void onDisconnectException(Exception e, SocketIOClient client) {
		log.error(e.getMessage(), e);
		if(enableLog)
			 log.cacheLog(Level.ERROR, "Error Message:"+e.getMessage()+",SessionId:"+client.getSessionId().toString()+",remoteAddr:"+client.getRemoteAddress().toString(), "onDisconnectException");
	
	}
	
	@Override
	public void onConnectException(Exception e, SocketIOClient client) {
		log.error(e.getMessage(), e);
		if(enableLog)
			 log.cacheLog(Level.ERROR, "Error Message:"+e.getMessage()+",SessionId:"+client.getSessionId().toString()+",remoteAddr:"+client.getRemoteAddress().toString(), "onConnectException");
	}
	
	
	@Override
	public boolean exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
		log.error(e.getMessage(), e);
		return false;//方法中返回true才是不抛出异常
	}
	
	@Override
	public void onPingException(Exception e, SocketIOClient client) {
		log.error(e.getMessage(), e);
	}
}
